package com.xzl.xep.web.interseptor;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.xzl.xep.common.springmvc.SpringContextHolder;
import com.xzl.xep.common.utils.CookieUtil;
import com.xzl.xep.pojo.Operator;
import com.xzl.xep.service.OperatorService;

/**
 * 验证用户登陆拦截器
 * 
 * @author Maty Chen
 * @date 2011-3-13 下午09:02:00
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
	
	public String[] allowUrls ;
	

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		String url = request.getRequestURI().replace(request.getContextPath(), "");
	
		logger.debug(url);
		
		if(isAllowUrl( url)) return true;
		
		
		Operator  op= (Operator) request.getSession().getAttribute(WebConstants.SESSION_OPERATOR);

		// 如果session中没有operator对象
		if (null == op) {
			CookieUtil cookieUtil = new CookieUtil(request,response);
			
			String operator_id = cookieUtil.getValue(Config.getLong(WebConstants.CONFIG_SYS_LOGIN_TIMEOUT), WebConstants.COOKIE_OPERATOR_ID);
			
			if(operator_id == null){
				logger.debug("用户无cookie信息！");
				return noLogin(request,response);
			}
			
			String ip;
			    
			 if (request.getHeader("x-forwarded-for") == null) {
				ip= request.getRemoteAddr();
			 }else{
				ip = request.getHeader("x-forwarded-for");
			 }
				 
			OperatorService service = SpringContextHolder.getBean("operatorServiceImpl");
			 
			op = service.loadObject(Operator.class, new Long(operator_id));
			
			if(op == null) return noLogin(request,response);
			
			if(ip.equals(op.getLastLoginIp()))
				request.getSession().setAttribute(WebConstants.SESSION_OPERATOR,op );
			else {
				logger.debug("用户ip 与数据库最后登录ip不一致！");
				return noLogin(request,response);
			}
				
		}
	
		return true;

	}
	
	
	private void returnAjaxNoLogin(HttpServletResponse response) throws IOException{
		response.setHeader("session-status", "timeout");
		response.getWriter().print("");
	}
	
	private boolean isAllowUrl(String requestUrl){
		 if(null != allowUrls && allowUrls.length>=1)  
            for(String url : allowUrls) {    
                if(requestUrl.contains(url)) {    
                    return true;    
                }    
            } 
		 
		 return false;
	}
	
	private boolean noLogin(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String requestedWith = request.getHeader("x-requested-with");
		// ajax请求
		if (requestedWith != null && "XMLHttpRequest".equals(requestedWith)) {
			returnAjaxNoLogin(response);
		} else {
			// 普通页面请求
			response.sendRedirect(request.getContextPath() + "/login");
		}
		return false;
	}
}
